<?php

use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Illuminate\Support\Facades\DB;

class PermissionTableSeeder extends Seeder
{

    protected $guardName = 'api';

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();
        $tableNames = config('permission.table_names');
        DB::statement('SET FOREIGN_KEY_CHECKS=0;');
        DB::table($tableNames['model_has_permissions'])->truncate();
        DB::table($tableNames['model_has_roles'])->truncate();
        DB::table($tableNames['role_has_permissions'])->truncate();
        DB::table($tableNames['permissions'])->truncate();
        DB::table($tableNames['roles'])->truncate();
        DB::statement('SET FOREIGN_KEY_CHECKS=1;');

        $this->permission([
            ['name' => 'all', 'text' => '全部权限'],
            ['name' => 'permission:zx', 'text' => '整形权限'],
            ['name' => 'permission:kq', 'text' => '口腔权限'],
        ]);

        Role::create($this->mergeGuard(
            ['name' => 'admin', 'text' => '超级管理员']
        ))->givePermissionTo('all');
        Role::create($this->mergeGuard(
            ['name' => 'user:zx', 'text' => '整形使用者']
        ))->givePermissionTo('permission:zx');
        Role::create($this->mergeGuard(
            ['name' => 'user:kq', 'text' => '口腔使用者']
        ))->givePermissionTo('permission:kq');

    }

    protected function permission($arr)
    {
        collect($arr)->each(function ($item) {
            $item = $this->mergeGuard($item);
            Permission::create($item);
        });
    }

    protected function mergeGuard($item)
    {
        return array_merge($item, ['guard_name' => $this->guardName]);
    }
}
